<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 12-8-14
 * Time: 上午10:09
 * To change this template use File | Settings | File Templates.
 */
class Model_Weiqi_User extends MY_Model
{
    const INTERFACEURL  = 'http://club.duiyi.tom.com/service/query.aspx';//接口地址

   	const CHESSPAYERTOP = 1;//棋友会排行榜
   	const CHESSTOP      = 2;//对弈排行榜
   	const WEALTHTOP     = 3;//财富排行榜
   	const ONEUSERINFO   = 4;//单个用户信息
   	const USERNICKNAME  = 5;//获取昵称接口
   	const GIFTPROPS     = 6;//赠送用户道具

    const NEWUSERINFO   = 7;//获取新的个人信息
    const GETUSERINGOT  = 8;//获取用户元宝

   	const TOPINFOLIMIT  = 10;//排行信息条数
   	const INTERFACEKEY  = 'TOMddU3&d3*Dk3%@JXCS38JFi(dk09%$37'; //接口KEY

   	public $fileTime    = 3600;//文件缓存时间

    /**
     * 获取一个用户相关数据
     *
     * @param $passport
     * @return bool|string
     */
    public function getOneUserInfo($passport)
   	{
   		if (empty($passport)) return false;

   		$type = self::ONEUSERINFO;
   		$content = $this->isData($passport.$type);
   		if ($content) return $content;

   		$sign = md5($type.self::INTERFACEKEY);
   		$url  = self::INTERFACEURL."?Type=$type&Sign=$sign&rolename=$passport";

   		$content = $this->fileGetContent($url);
   		$this->setData($passport.$type, $content);
   		return $content;
   	}

    /**
     * 获取用户昵称数据
     *
     * @param $nickname
     * @return bool|string
     */
    public function getUserNickName($nickname)
   	{
   		if (empty($nickname)) return false;

   		//$encode = mb_detect_encoding($nickname, array('ASCII','UTF-8','GB2312','GBK','BIG5'));
   		$nickname = iconv('utf-8', 'gb2312', $nickname);
   		//echo $nickname;
   		$type = self::USERNICKNAME;
   		$content = $this->isData($nickname.$type);

   		if ($content) return $content;
   		$sign = md5($type.self::INTERFACEKEY);
   		$url  = self::INTERFACEURL."?Type=$type&Sign=$sign&username=".urlencode($nickname);
   		//echo $url;
   		$content = $this->fileGetContent($url);
   		$this->setData($nickname.$type, $content);
   		return $content;
   	}

    /**
     * 获取排行榜数据
     *
     * @param int $type
     * @param int $limit
     * @return bool|string
     * notes: type
     *  1 棋友会排行榜
     *  2 对弈排行榜
     *  3 财富排行榜
     */
    public function getTopInfo($type = self::CHESSPAYERTOP, $limit = self::TOPINFOLIMIT)
   	{
   		$content = $this->isData($type.$limit);
   		if ($content) return $content;

   		$sign = md5($type.self::INTERFACEKEY);

   		$url  = self::INTERFACEURL."?Type=$type&Sign=$sign&top=$limit";
   		$content = $this->fileGetContent($url);

   		$this->setData($type.$limit, $content);
   		return $content;
   	}

   	/**
   	 * @name 赠送用户道具
   	 * @param string $passport
   	 * @param int    $propsId
   	 * @param int    $count
   	 * @return bool
   	 * uuid:C2F41010-65B3-11d1-A29F-00AA00C14882
   	 * uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882
   	 */
   	public function giftProps($passport, $propsId, $count = 0)
   	{
        if (empty($passport)) return false;
        if (!$propsId) return false;

        $type      = self::GIFTPROPS;
        //$fileCache = Hjlib_Load::Cache()->fileCache();
        //$fileCache->setPath($this->filePath);

        $sign    = md5($type.self::INTERFACEKEY);
        $url     = self::INTERFACEURL."?Type=$type&Sign=$sign&username=$passport&propertyid=$propsId&count=$count";

        $content = $this->fileGetContent($url);
        if (empty($content)) {
            return false;
        } else {
            $this->load->driver('cache');
            $this->cache->file->save(APPPATH.'logs/gift_props.log', $passport.', GIFT ID:'.$propsId.', RETURN VALUE:'.$content."\n", $this->fileTime);
            //$fileCache->set('gift_props.log', $passport.', GIFT ID:'.$propsId.', RETURN VALUE:'.$content."\n", 0, 'a+');
        }
        return $content;
   	}

    /**
     * 获取用户信息 -- 信息更丰富、更详细
     *
     * @param $passport
     * @param int $roleInfoType
     * @return bool|string
     *
     * roleInfoType = 1 是获取一般信息
     * roleInfoType = 2 是获取用户好友列表
     * roleInfoType = 3 是获取用户黑名单
     * roleInfoType = 4 是获取百宝箱内道具种类及数量
     * roleInfoType = 5 是获取保险箱内道具种类及数量
     * roleInfoType = 6 是获取用户最近20局战绩
     */
    public function NewUserInfo($passport, $roleInfoType = 1)
    {
        if ( empty($passport) ) return false;

        $type = self::NEWUSERINFO;
        $content = $this->isData($passport.$type.$roleInfoType);
        if ($content) return $content;

        $sign = md5($type.self::INTERFACEKEY);

        $url  = self::INTERFACEURL."?Type=$type&Sign=$sign&rolename=$passport&roleInfoType=".$roleInfoType;
        $content = $this->fileGetContent($url);

        $this->setData($passport.$type.$roleInfoType, $content);
        return $content;
    }

    /**
     * 获取用户元宝数量
     *
     * @param $passport
     * @return bool|string
     */
    public function getUserIngot($passport)
    {
        if ( empty($passport) ) return false;

        $type = self::GETUSERINGOT;

        $sign = md5($type.self::INTERFACEKEY);

        $url  = self::INTERFACEURL."?Type=$type&Sign=$sign&rolename=$passport";
        $content = $this->fileGetContent($url);

        $this->setData($passport.$type, $content);

        return $content;
    }


   	/**
   	 * @name 充值接口
   	 * @param string $passport
   	 * @param int    $amount
   	 * @param int    $orderSn
   	 * @return bool
   	 *//*
   	public function recharge($passport, $amount, $orderSn)
   	{
   		//调用游戏方接口，进行充值对换
   		$sign   = md5($passport.$amount.$orderSn.GAMEPAYKEY);
   		$data   = array('fillAccount'=>$passport, 'trueMoney'=>$amount, 'fillOrder'=>$orderSn, 'channel'=>GAMEPAYCHANNEL, 'sign'=>$sign,);
   		$status = $this->post(GAMEPAYPATH, $data);
   		$strs   = explode('&', $status);
   		foreach ($strs as $v)
   		{
   			$a = explode('=', $v);
   			$returnData[$a[0]] = $a[1];
   		}
   		return $returnData;
   	}
   	//*/


    /**
     * 格式化数据 XML to ARRAY
     *
     * @param $content
     * @return string | boolean
     */
    public function formatData($content)
   	{
        $content = str_replace('&', '', $content);

        $this->load->library('xml');
        $this->xml->parseString($content);
        $data = $this->xml->getTree();

        //$data = $this->xml->xml_unserialize($content);
        if (!isset ($data['root'])) {
            $data['root'] = array();
        }

        return $data['root'];
   	}

    /**
     * 是否有数据
     *
     * @param $mark
     * @return bool
     */
    private function isData($mark)
   	{
        $fileName = md5($mark).'.txt';
        //$fileCache = Hjlib_Load::Cache()->fileCache();
        //$fileCache->setPath($this->filePath);

        $this->load->driver('cache');

        //if (!file_exists($this->filePath.$fileName)) return false;

        //if (filemtime($this->filePath.$fileName) < time()) return false;

        //$data = $fileCache->get($fileName, 1);
        $data = $this->cache->file->get($fileName);
        return $data;
   	}

    /**
     * 设置数据
     *
     * @param $mark
     * @param $content
     * @return bool
     */
    private function setData($mark, $content)
   	{
   		if (empty($mark) || empty($content)) return false;

   		$fileName = md5($mark).'.txt';
   		//$fileCache = Hjlib_Load::Cache()->fileCache();
   		//$fileCache->setPath($this->filePath);
       $this->load->driver('cache');
       $this->cache->file->save($fileName, $content, $this->fileTime);
   		//$fileCache->set($fileName, $content, $this->fileTime);
   	}

    /**
     * 调用接口获取数据
     *
     * @param $url
     * @return bool|string
     */
    private function fileGetContent($url)
   	{
   		if (empty($url)) return false;

   		$content = file_get_contents($url);
   		$encode = mb_detect_encoding($content, array('ASCII','UTF-8','GB2312','GBK','BIG5'));
   		$content = iconv($encode, 'utf-8', $content);
   		return $content;
   	}

    /**
     * post数据
     *
     * @param $url
     * @param null $post
     * @return string
     */
    private function post($url, $post = null)
   	{
   	    $context = array();
   	    if (is_array($post))
   	    {
   	        ksort($post);
   	        $context['http'] = array( 'method' => 'POST', 'content' => http_build_query($post, '', '&'), );
   	    }
   	    return file_get_contents($url, false, stream_context_create($context));
   	}
}
